package com.dalongxin.work.data;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@DatabaseTable(tableName="contact")
public class Contact implements Serializable {
    @DatabaseField
    private int id;
    @DatabaseField
    private String userName;
    @DatabaseField
    private String phone;
    @DatabaseField
    private String email;

    private Department department;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public static Contact parseFromJson(JSONObject jsonObject) {
        Contact contact = new Contact();
        contact.id = jsonObject.optInt("id");
        contact.userName = jsonObject.optString("userName");
        contact.phone = jsonObject.optString("phone");
        contact.email = jsonObject.optString("email");
        return contact;
    }

    public static List<Contact> parseFromJsonList(JSONArray jsonArray) {
        List<Contact> list = new ArrayList<>();
        if(jsonArray != null && jsonArray.length() > 0) {
            for(int i=0;i<jsonArray.length();i++) {
                Contact item = parseFromJson(jsonArray.optJSONObject(i));
                if(item != null)list.add(item);
            }
        }
        return list;
    }

    public static List<Contact> parseFromList(List<Department> departments) {
        List<Contact> contactList = new ArrayList<>();
        if(departments != null && departments.size() > 0) {
            for(Department department : departments) {
                List<Contact> cc = department.getUserList();
                if(cc != null && cc.size() > 0) {
                    for(Contact c : cc) {
                        c.setDepartment(department);
                        contactList.add(c);
                    }
                }
            }
        }
        return contactList;
    }
}
